#include <stdio.h>
#include <math.h>

// 定义多项式的系数
// 计算多项式值查看语雀文档：https://pudutech.yuque.com/vxclsy/ytupgx/qvin8gbw8p9ut7b6
#define A -2.97967366e-06
#define B 1.70126107e-03
#define C 1.00979709
#define D 4.01233333

// 定义多项式函数
double polynomial(double x) {
    return A * pow(x, 3) + B * pow(x, 2) + C * x + D;
}

// 目标函数 f(x) = ax^3 + bx^2 + cx + d - flow_rate
double target_function(double x, double flow_rate) {
    return polynomial(x) - flow_rate;
}

// 使用二分法求解多项式方程的根
double find_speed_from_flow_rate(double flow_rate, double lower_bound, double upper_bound, double tolerance) {
    if (target_function(lower_bound, flow_rate) * target_function(upper_bound, flow_rate) >= 0) {
        printf("Error: The root is not bracketed between the given bounds.\n");
        return -1;
    }

    double mid_point;
    while ((upper_bound - lower_bound) >= tolerance) {
        mid_point = (lower_bound + upper_bound) / 2;

        if (target_function(mid_point, flow_rate) == 0.0)
            break;

        if (target_function(mid_point, flow_rate) * target_function(lower_bound, flow_rate) < 0)
            upper_bound = mid_point;
        else
            lower_bound = mid_point;
    }

    return (lower_bound + upper_bound) / 2;
}

int main() {
    // 设置初始参数
    double lower_bound = 0;  // 转速不能为负
    double upper_bound = 600;  // 假设转速不会超过这个值
    double tolerance = 1e-5;  // 精度要求

    // 获取用户输入的出水量
    double flow_rate;
    printf("Please enter the water output (L/min): ");
    scanf("%lf", &flow_rate);

    if (flow_rate <= 0) {
        printf("must be positive。\n");
        return 1;
    }

    // 计算对应的转速
    double speed = find_speed_from_flow_rate(flow_rate, lower_bound, upper_bound, tolerance);

    if (speed != -1) {
        printf(" speed is: %.2f rpm\n", speed);
    } else {
        printf("No valid RPM could be found。\n");
    }

    return 0;
}